<template>
  <div ref="mapRef" class="com-full" style="background-color: transparent"></div>
  <div
    :id="mapId"
    class="com-full"
    style="position: fixed; left: -100%; opacity: 0; pointer-events: none"
  ></div>
</template>

<script setup>
import { onMounted, nextTick, watch, shallowRef, ref } from "vue";
import { guid } from "@/utils";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-rotatedmarker";
import "proj4leaflet";
import "leaflet-mouse-position";

const props = defineProps({
  pointList: {
    type: Array,
    default: () => [],
  },
});

const mapRef = ref();

const mapId = ref(guid());
const map = shallowRef();

//修改时间
const changeTime = (data) => {
  if (data) {
    let time = new Date(data);
    let day = time.getDate();
    let hour = time.getHours();
    let min = time.getMinutes();
    if (min < 10) {
      min = "0" + min;
    }
    if (hour < 10) {
      hour = "0" + hour;
    }
    if (day < 10) {
      day = "0" + day;
    }
    return day + " " + hour + ":" + min;
  } else {
    return null;
  }
};
const markSet = {};
const getNewPoints = async (list = []) => {
  // 存储当前被拖拽的标记和它的先前位置
  var currentDraggableMarker = null;
  var previousPosition = null;
  console.log("list11", list);
  const data = await init(list.map((item) => [item?.lo, item?.la]));
  // const data = list;
  console.log("data11", data);
  await nextTick();
  setTimeout(() => {
    data.forEach((element, i) => {
      const text = {
        id: list?.[i]?.flightType === 1 ? list?.[i]?.flightNoA : list?.[i]?.flightNoD,
        status: list?.[i]?.atcEstripStatus ?? "--",
        staBefor:
          list?.[i]?.flightType === 1
            ? changeTime(list?.[i]?.staBeforA) ?? "--"
            : changeTime(list?.[i]?.staBeforB) ?? "--",
        ptd: changeTime(list?.[i]?.ptd) ?? "--",
        flightType: list?.[i]?.flightType,
      };
      let color = text?.flightType === 1 ? "rgba(34, 149, 215, 0.8)" : "rgb(255 ,235, 1 , 0.8)";
      var position = [element.y, element.x];
      L.circle(position, {
        color: color,
        radius: 1300,
      }).addTo(map.value);
      let marker = null;
      if (!markSet.hasOwnProperty(list?.[i]?.flightId)) {
        marker = L.marker(position, {
          icon: L.divIcon({
            html: `
            <div
              style="
                border-radius: 4px;
                width: fit-content;
                font-size: 10px;
                color: #fff;
                padding: 10px;
                gap: 5px;
                position: relative;
                overflow: hidden;
                background-color: ${text?.flightType === 1 ? "#29CF9C80" : "#CF982980"}
              ">
              <div style="backdrop-filter: blur(3px); position: absolute; left: 0; top: 0;width: 100%;height: 100%"></div>
              <div style="display: flex; flex-direction: column; gap: 5px; opacity: 0">
                <div>航班号:${text.id}</div>
                <div>电子进程单状态:${text.status}</div>
                <div>计划离港:${text.staBefor}</div>
                <div>PTD:${text.ptd}</div>
              </div>
              <div style="padding: 10px;position: absolute;left: 0;top: 0;z-index: 1;display: flex;flex-direction: column;gap: 5px;">
                <div>航班号:${text.id}</div>
                <div>电子进程单状态:${text.status}</div>
                <div>计划离港:${text.staBefor}</div>
                <div>PTD:${text.ptd}</div>
              </div>
            </div>
          `,
            className: "",
            iconSize: [130, 140],
            iconAnchor: [65, 70],
            shadowUrl: null,
          }),
          draggable: true, // 初始时不可拖拽
        }).addTo(map.value);
        var polyline = L.polyline([position, position], { color: color, weight: 2 }).addTo(
          map.value
        );
        //激活移动的定盘
        marker.on("dragstart", function () {
          currentDraggableMarker = marker;
          previousPosition = [...position]; // 复制当前位置作为先前位置
        });

        // 添加拖拽结束事件监听器
        marker.on("drag", function (event) {
          if (currentDraggableMarker === marker) {
            var newPosition = marker.getLatLng();

            // 更新连接线
            polyline.setLatLngs([previousPosition, newPosition]);
          }
        });
        markSet[list?.[i]?.flightId] = marker;
      } else {
        marker = markSet[list?.[i]?.flightId];
        marker.setLatLng(L.latLng(element.y, element.x));
      }
    });
  }, 0);
};

const init = (points = []) => {
  console.log("进入gis服务的经纬度转换", points);
  return new Promise((resolve, reject) => {
    window.require(
      [
        "js/BNFactory",
        // "js/jquery-3.2.1.min",
      ],
      function (BNFactory) {
        let mapa = new BNFactory("2202", {
          id: mapId.value,
          options: {
            logo: false,
            slider: true,
            isDoubleClickZoom: false,
          },
        });

        let BNmapUtil = new BNFactory("BNmapUtil", mapa);
        BNmapUtil.doLatLngTransformMapXY(
          points,
          4326,
          mapa.spatialReference,
          function (data) {
            console.log("机场GIS的转换结果", data);
            resolve(data);
          },
          function (err) {
            console.log("机场GIS的转换结果报错了", err);
            reject(err);
          }
        );
      },
      function (err) {
        reject(err);
      }
    );
  });
};
const mapInit = async () => {
  map.value = null;
  await nextTick();
  let CRS_3857 = new L.Proj.CRS("EPSG:3857", "+proj=longlat +ellps=GRS80+no defs", {
    resolutions: [
      21.16670900008467, 13.229193125052918, 5.291677250021167, 2.6458386250105836,
      1.3229193125052918, 0.5291677250021167, 0.26458386250105836, 0.13229193125052918,
      0.05291677250021167,
    ],
    origin: [-2.1146465429211874e7, 2.023531600006042e7],
  });
  map.value = L.map(mapRef.value, {
    crs: CRS_3857,
    minZoom: 0,
    maxZoom: 9,
    attributionControl: false,
  }).setView([302117.0486283762, 1067769.5238614036], 2);

  // 底图瓦片
  const baseLayer = L.tileLayer(import.meta.env.VITE_MAP_LEAFLET_URL);

  baseLayer.addTo(map.value);
};
watch(
  () => props.pointList,
  async (val) => {
    if (markSet) {
      console.log(123, markSet);
    }

    if (!map.value) {
      await mapInit();
    }
    const keys = Object.keys(markSet);
    keys.forEach((key) => {
      const index = val.findIndex((ele) => ele.flightId + "" === key + "");
      if (index === -1) {
        delete markSet[key];
      }
    });
    if (markSet) {
      console.log(456, markSet);
    }
    getNewPoints(val);
  },
  { immediate: true, deep: true }
);
onMounted(async () => {
  if (!window.require) return;
  await mapInit();
});
</script>

<style scoped lang="scss">
:deep(.leaflet-tooltip) {
  background-color: transparent;
  border: 0;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0);
  color: #fff;
}
</style>
